﻿//Description:废品单集成
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:Wangjh
//create Date:2018-3-15
//Rewriter:
//Rewrite Date:
using System; 
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using UFC.DBUtility;
using UFC.Common;
using System.Configuration;
using System.Data.OracleClient;
using System.Xml;

namespace MESContainerStepScrap
{
   public  class SendStepScrap
    {
       private const string m_RecordType = "StepScrap";
       public void RunStepScrapSync()
       {
           DataTable mydt = GetContainerStepScrap();
           if (mydt == null || mydt.Rows.Count <= 0)
           {
               LogHelp.WriteLog("没有可处理的废品单记录");
           }
           Dictionary<string, string> strList;
          // ERPService.PS_SAPServicesHttpService sap = new ERPService.PS_SAPServicesHttpService();
           foreach (DataRow dr in mydt.Rows)
           {
               LogHelp.WriteLog("处理废品单记录开始" + dr["CONTAINERID"].ToString());
               strList = new Dictionary<string, string>();

               strList.Add("ZQMT017-QMNUM", dr["QMNUM"].ToString());//通知单编号
               strList.Add("ZQMT017-MATNR", dr["MATNR"].ToString());//物料号
               strList.Add("ZQMT017-FERTAUFNR", dr["FERTAUFNR"].ToString());//生产订单号
               strList.Add("ZQMT017-FERTVORNR", dr["FERTVORNR"].ToString());//MES工序
               strList.Add("ZQMT017-ZMESGXTXT", dr["ZMESGXTXT"].ToString());//MES工序描述
               strList.Add("ZQMT017-UVORN", dr["UVORN"].ToString());//子工序
               strList.Add("ZQMT017-ZLTXA1", dr["ZLTXA1"].ToString());//子工序描述
               strList.Add("ZQMT017-ZZFPLX", dr["ZZFPLX"].ToString());//废品类型
               strList.Add("ZQMT017-ZBFLJLX", dr["ZBFLJLX"].ToString()); //报废零件类型	
               strList.Add("ZQMT017-ZZFPPLY", dr["ZZFPPLY"].ToString());//生产单位Z2
               strList.Add("ZQMT017-ZFPDBH", dr["ZFPDBH"].ToString());// 废品单编号  	
               strList.Add("ZQMT017-ZJX", dr["ZJX"].ToString());//	型别
               strList.Add("ZQMT017-ZPCH", dr["ZPCH"].ToString());//机加批次
               strList.Add("ZQMT017-ZLPH", dr["ZLPH"].ToString());//炉批号
               strList.Add("ZQMT017-ZZRDW", dr["ZZRDW"].ToString());//责任单位
               strList.Add("ZQMT017-ZZRZ", dr["ZZRZ"].ToString());//	责任者
               strList.Add("ZQMT017-ZJYY", dr["ZJYY"].ToString());//检验员
               strList.Add("ZQMT017-ZJYSZR", dr["ZJYSZR"].ToString());//检验室主任
               strList.Add("ZQMT017-ZGD", dr["ZGD"].ToString());//工段
               strList.Add("ZQMT017-ZFPSL", dr["ZFPSL"].ToString()); //	废品数量
               strList.Add("ZQMT017-ZFPZL", dr["ZFPZL"].ToString());//废品重量
               strList.Add("ZQMT017-ZDW", dr["ZDW"].ToString());//单位     
               strList.Add("ZQMT017-ZYWLH", dr["ZYWLH"].ToString());//原料物料号
               strList.Add("ZQMT017-ZCLPH1", dr["ZCLPH1"].ToString());//材料牌号
               strList.Add("ZQMT017-ZYWLPC1", dr["ZYWLPC1"].ToString());//原料收货批次号
               strList.Add("ZQMT017-ZBZ", dr["ZBZ"].ToString());//备注
               strList.Add("ZQMT017-QMGRP", dr["QMGRP"].ToString());//编码-代码组
               strList.Add("ZQMT017-QMCOD", dr["QMCOD"].ToString());//编码-代码
               strList.Add("ZQMT017-ZZTTXT", dr["ZZTTXT"].ToString());//主题长文本（缺陷文本）
               strList.Add("ZQMT017-POSNR", dr["POSNR"].ToString());//缺陷-排序号
               strList.Add("ZQMT017-FEGRP", dr["FEGRP"].ToString());//缺陷-代码组
               strList.Add("ZQMT017-FECOD", dr["FECOD"].ToString());//编码-代码
               strList.Add("ZQMT017-FETXT", dr["FETXT"].ToString());//缺陷短文本描述
               strList.Add("ZQMT017-ZQXTXT", dr["ZQXTXT"].ToString());//行项目缺陷长文本
               string strXML = CreateXMLForStepScrap(strList);
               LogHelp.WriteLog(strXML);
               //ERPService.ErpAndAppSyncData mm = new ERPService.ErpAndAppSyncData();
               //mm.ReqMsg = strXML;
               //ERPService.ErpAndAppSyncDataResponse result = sap.ErpAndAppSyncData(mm);
               //if (result != null)
               //{
               string strMsg = "";
               // strMsg = result.RespMsg;
               if (GetERPRcvXML(strMsg))
               {
                   UpdateStepScrap(dr["ContainerStepScrapInfoID"].ToString());
                   OracleDAL.InsertSyncRecord(dr["ContainerStepScrapInfoID"].ToString(), m_RecordType, "成功", 0);
               }
               else 
               {
                   OracleDAL.InsertSyncRecord(dr["ContainerStepScrapInfoID"].ToString(), m_RecordType, strMsg, 0);
               }

           }

       }

       /// <summary>
       /// 批次工序废品通知单记录获取
       /// </summary>
       /// <returns></returns>
       DataTable GetContainerStepScrap() {
           string strSql = @"
                            SELECT T.*  FROM ContainerStepScrapInfo T
                            LEFT JOIN WRITETOERPRECORD ERP
                            ON ERP.RECORDID = T.ContainerStepScrapInfoID
                            ";
           strSql += string.Format(" AND ERP.RECORDTYPE = '{0}'", m_RecordType);
           strSql += @" WHERE T.ISUSE = 0
                        AND T.ISINTEGRATION = 1
                        AND ERP.RECORDID IS NULL";
           DataSet myDS = OracleHelper.Query(strSql);
           if (myDS == null)
           {
               return null;
           }
           if (myDS.Tables.Count == 0)
           {
               return null;
           }
           return myDS.Tables[0];
       }

       /// <summary>
       /// 更新报废单信息转接标记
       /// </summary>
       /// <param name="ContainerStepScrapInfoID"></param>
       /// <param name="IsIntegration"></param>
       /// <returns></returns>
       private bool UpdateStepScrap(string ContainerStepScrapInfoID )
       {
           string strSql = @"UPDATE ContainerStepScrapInfo SET ISINTEGRATION = 0";

           strSql += " WHERE ContainerStepScrapInfoID = :v_recordid";
           OracleParameter[] insertParam = new OracleParameter[1];

           insertParam[0] = new OracleParameter();
           insertParam[0].ParameterName = ":v_recordid";
           insertParam[0].OracleType = OracleType.VarChar;
           insertParam[0].Direction = ParameterDirection.Input;
           insertParam[0].Value = ContainerStepScrapInfoID;

           int i = OracleHelper.ExecuteSql(strSql, insertParam);
           if (i > 0)
               return true;
           else
               return false;
       }
       /// <summary>
       /// 创建xml字符串
       /// </summary>
       /// <param name="strList"></param>
       /// <returns></returns>
       private string CreateXMLForStepScrap(Dictionary<string, string> strList)
       {

           XmlDocument doc = new XmlDocument();
           doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
           XmlNode ReqNode = doc.CreateElement("ReqMsg");
           XmlNode headerNode = doc.CreateElement("header");
           XmlNode senderNode = doc.CreateElement("sendSysName");
           senderNode.InnerText = "APP_MES";
           XmlNode rcvNode = doc.CreateElement("rcvSysName");
           rcvNode.InnerText = "APP_ERP";
           XmlNode extNode = doc.CreateElement("extConfig");
           extNode.AppendChild(doc.CreateElement("isReTry"));
           extNode.LastChild.InnerText = "false";
           extNode.AppendChild(doc.CreateElement("FunName"));
           extNode.LastChild.InnerText = "ZPPF_MES_06";
           headerNode.AppendChild(senderNode);
           headerNode.AppendChild(rcvNode);
           headerNode.AppendChild(extNode);
           ReqNode.AppendChild(headerNode);
           XmlNode documentNode = doc.CreateElement("document");
           string strData = "<ALCNRINFO>";
           foreach (KeyValuePair<string, string> _key in strList)
           {
               strData = string.Format("{0}<{1}>{2}</{1}>", strData, _key.Key, _key.Value);
           }
           strData += "</ALCNRINFO>";
           documentNode.AppendChild(doc.CreateCDataSection(strData));
           ReqNode.AppendChild(documentNode);
           doc.AppendChild(ReqNode);
           return doc.InnerXml;
       }

       /// <summary>
       /// 获取ERP反馈XML
       /// </summary>
       /// <param name="strXML"></param>
       /// <returns></returns>
       private bool GetERPRcvXML(string strXML)
       {
           XmlDocument doc = new XmlDocument();
           doc.LoadXml(strXML);
           string isSuccess = doc.SelectSingleNode("RespMsg/header/isSuccess").InnerText;
           string meaasge = doc.SelectSingleNode("RespMsg/header/message").InnerText;

           if (isSuccess == "true" || meaasge == "S")
               return true;
           else
           {
               LogHelp.WriteLog(meaasge);
               return false;
           }
       }

    }
}
